<template>
  <div id="layout" :class="knowledgeBg" @click="edit">
    <!-- <BackgroundVideoContainer v-if="route.name == 'home'" /> -->

    <Header @click.stop @saveEdit="saveEditModel" @exitEdit="exitEditModel" @zoomEdit="zoomEditModel"
      @hkreconnect="arhkreconnect" :isZoom="isZoom"></Header>
    <!-- 头部三个统计  -->
    <transition appear name="custom-classes-transition"
      enter-active-class="animate__animated animate__faster  animate__fadeIn "
      leave-active-class="animate__animated animate__faster animate__fadeOut ">
      <tab v-if="!israload && Model == 'dashboard'"></tab>
    </transition>
    <!-- 视频管理 -->
    <transition appear name="custom-classes-transition"
      enter-active-class="animate__animated animate__faster  animate__fadeIn "
      leave-active-class="animate__animated animate__faster animate__fadeOut ">
      <FullScreenCard :dialogShow="uf.cardShow" @closeDialog="monitorCloseDialog">
        <MonitorFullscreen />
      </FullScreenCard>
    </transition>
    <!-- 鹰眼管理 -->
    <transition appear name="custom-classes-transition"
      enter-active-class="animate__animated animate__faster  animate__fadeIn "
      leave-active-class="animate__animated animate__faster animate__fadeOut ">
      <FullScreenCard :dialogShow="uf.hkarShow" @closeDialog="hkarCloseDialog" :padding="0" :height="100">
        <!-- <hkarVideo v-if="uf.hkarShow"></hkarVideo> -->
        <EagleEyePerspective v-if="uf.hkarShow" />
      </FullScreenCard>
    </transition>
    <Cdialog :visible="visiable" :title="'修改密码'" width="700" @closeDialog="closeDialoglogin">
      <ChangePassword />
    </Cdialog>
    <!-- 展开/收缩操作 -->
    <rightbutton v-if="Model == 'dashboard'"></rightbutton>
    <!-- 点位数据 -->

    <template v-for="item in eqData" v-if="showPoint">
      <cPopover @mousemove.stop :options="item" v-if="item.locationId == locationIndex" @cancel="EditcancelModel"
        @delect-point="delectPointModel" :key="item.id" @close-pop="closePop" ref="cpopoverRef">
      </cPopover>
    </template>
    <!-- 页面切换 -->
    <RouterView v-if="Model == 'dashboard'"></RouterView>
    <!-- 底部导航 -->
    <template v-if="Model == 'dashboard'">
      <tabbar></tabbar>
    </template>
    <!-- 配置点位 -->
    <template v-if="Model == 'edit' && !isZoom">
      <editPoint @click.stop @selectType="changeSelect"></editPoint>
    </template>
    <!-- <redialog></redialog> -->
    <CustomDialog />
  </div>
</template>

<script setup lang="ts">
// import { edit, Editcancel, delectPoint, saveEdit, exitEdit } from '@/utils/pointEdit'
import {
  ref,
  computed,
  watch,
  nextTick,
  onMounted,
  onBeforeMount,
  toRefs,
  onUnmounted,
} from "vue";
import { RouterView, useRoute } from "vue-router";
import { useFullScreenCard } from "@/stores/slg/fullscreencard";
import MonitorFullscreen from "./components/monitor-fullscreen.vue";
import EagleEyePerspective from "./components/eagle-eye-perspective.vue";
import ChangePassword from "../changePassword/index.vue";
import { UseModel } from "@/stores/model";
import { UseLocation } from "@/stores/location";
import cPopover from "../../components/cPopover/index.vue";
import { getEqStatus, getEqType, getEquipmentIds } from "@/api/equipment";
import emits from "@/utils/emits";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { Notification } from "./components/index";
import { getAlertData } from "@/api/alert";
import { useIds } from "@/stores/screen/ids";
import { UseLocationaside } from "@/stores/locationaside";
import { useAppStore } from "@/stores/modules/app";
import { UseLocationPonit } from "@/stores/locationPoint";
// import hkarVideo from '@/components/hkar/index.vue'
import { getEqPoint, savePoint } from "@/api/equipment";
import { getRtsp } from "@/api/screen/equipment";
// 提前加载背景图片
import location0 from "@/assets/image/dashboard/location/港口总览.jpg";
import location1 from "@/assets/image/dashboard/location/01区.jpg";
import location2 from "@/assets/image/dashboard/location/02区.jpg";
import { useBeforeunload } from "@/hooks/useBeforeunload";
import { initWsMsg } from "@/utils/wxmsg/config";
import { useLocationEq } from "@/stores/getEqByLocation";
import { storeToRefs } from "pinia";
import BackgroundVideoContainer from "./components/backgroundVideoContainer.vue";
import { points } from '@/common/common';
const cpopoverRef = ref();
const { setEqDataSelect } = useLocationEq();
const { initPointData, setPointData } = UseLocationPonit();
const { visiable } = storeToRefs(useAppStore());
const { setVisiable } = useAppStore(); //控制修改密码弹窗显隐
const locationaside = UseLocationaside(); //告警页面区域aside
const { resetIDs } = useIds(); //重新设置设备ids
const location = UseLocation(); //当前区域
const model = UseModel(); //表示大屏模式，看板or编辑
const uf = useFullScreenCard(); //控制tarbar组件显示页面
const knowledgeBg = ref("back1");
const israload = ref(false); //使用reload参数刷新页面
const eqData = ref(points); //点位数据
const showPoint = ref(false); //控制点位显隐
const eqType = ref([]); //设备类型
const selectEqType = ref(""); //选择的设备类型
const eqModel = ref(""); //选择的设备型号
const eqdirection = ref("");
const route = useRoute();
const isZoom = ref(false);
const closeDialoglogin = () => {
  emits.emit("closeLoginBox", false);
  setVisiable(false);
};
// 监控是否处于点位编辑模式
const pointEdit = computed(() => {
  return model.$state.edit;
});
// 获取当前位置index
const locationIndex = computed(() => {
  return location.$state.LocationIndex;
});
// 大屏模式
const Model = computed(() => {
  return model.$state.model;
});
// 提前加载图片
const initImage = () => {
  let imageData = [location0, location1, location2];
  for (let i of imageData) {
    let image = new Image();
    image.src = i;
    image.onload;
  }
};
// reload页面数据
const reload = () => {
  israload.value = true;
  console.log("首页接收到reload");
  nextTick(() => {
    console.log("首页接执行reload");
    israload.value = false;
  });
};
// 监控位置index进行背景图片的切换
watch(
  () => locationIndex.value,
  (newval) => {
    switch (newval) {
      case 0:
        knowledgeBg.value = "knowledgeBg";
        break;

      case 1:
        knowledgeBg.value = "knowledgeBg1";
        break;
      case 2:
        knowledgeBg.value = "knowledgeBg2";
        break;
      case 3:
        knowledgeBg.value = "knowledgeBg3";
        break;
      case 4:
        knowledgeBg.value = "knowledgeBg4";
        break;
    }
    console.log(location.$state, "newval");

    resetIDs(location.$state.locationArr[newval].code);
  },
  { immediate: false, deep: true }
);
// 判断区域下是否存在告警的点位
// const getLocationAlertDetail = () => {
//   console.log("判断。。。。。");

//   let data = [];
//   console.log(eqData.value, "vv1212");

//   eqData.value.forEach((item) => {
//     if (item.wsMsg[0] && item.wsMsg[0].handleStatus == "0") {
//       data.push(item.locationId);
//     }
//   });
//   locationaside.$state.locationArr = [
//     // { code: 'ALL', name: '全部', status: false },
//     { code: "LOCATION_01", name: "01区", status: false },
//     { code: "LOCATION_02", name: "02区", status: false },
//     // { code: "LOCATION_03", name: "03区", status: false },
//     // { code: "LOCATION_04", name: "04区", status: false },
//   ];
//   initPointData();
//   data.forEach((item) => {
//     if (item) {
//       locationaside.$state.locationArr[item - 1].status = true;
//       setPointData(item - 1);
//     }
//   });
//   console.log(data, "vv1212");
// };
//点位编辑模式
const edit = (event) => {
  if (Model.value == "edit" && pointEdit.value) {
    console.log(event.target);
    if (event.target.id != "layout") {
      ElMessage.warning("在这附近已经有点位了，请重新选择！");
      var body = document.querySelector("body");
      body.style.cursor = "default";
      model.Setedit(false);
      return;
    }
    let left = Math.floor((event.x / innerWidth) * 100) + "%";
    let top = Math.floor((event.y / innerHeight) * 100) + "%";
    let obj = {
      equipmentId: "",
      name: "",
      locationId: locationIndex.value,
      position: { top: top, left: left },
      location: "",
      wsMsg: [{}],
      popoverVisible: false,
      status: "onLine",
      equipmentLocationCode: "",
      editId: event.x * event.y,
      id: null,
      type: selectEqType.value,
      eqModel: eqModel.value,
      direction: eqdirection.value,
      eqCode: "",
      hasAi: false,
    };
    console.log(obj);
    eqData.value.push(obj);
    console.log(event.x, event.y, "位置信息");
    var body = document.querySelector("body");
    body.style.cursor = "default";
    model.Setedit(false);
    selectEqType.value = "";
  }
};

// 取消设备选择
const EditcancelModel = (id) => {
  // Editcancel(id, eqData.value)
  if (Model.value == "edit") {
    console.log(id);
    let index = eqData.value.findIndex(
      (item) => item.editId && item.editId == id
    );
    console.log(index);
    eqData.value.splice(index, 1);
  }
};
// 删除设备询问
const delectPointModel = async (code: string) => {
  // await delectPoint(code, eqData.value, getLocationAlertDetail, setEqDataSelect(code))
  // setEqDataSelect(code)
  // getLocationAlertDetail()
  // setEqDataSelect(code)
  ElMessageBox.confirm(`是否删除设备：${code}？一但确认无法取消！`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });

      eqData.value = eqData.value.filter((item) => {
        return item.equipmentLocationCode != code;
      });
      console.log(eqData.value, "删除设备index");
      // getLocationAlertDetail();
      setEqDataSelect(code);
    })
    .catch(() => { });
};
// 保存点位编辑
const saveEditModel = () => {
  // saveEdit(eqData.value, beforeInit)
  if (Model.value == "edit") {
    if (
      eqData.value.some(
        (item) =>
          !item.equipmentLocationCode || item.equipmentLocationCode == ""
      )
    ) {
      console.log(eqData.value);

      ElMessage.warning("存在没有配置的点位，请进行配置!");
      return;
    } else {
      ElMessageBox.confirm(`是否保存配置？`, "点位配置", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(async () => {
          let data = [];
          eqData.value.forEach((item) => {
            let eqObj = {
              equipmentLocationCode: item.equipmentLocationCode,
              position: item.position,
              locationId: item.locationId,
              id: item.id,
              direction: item.direction,
            };
            data.push(eqObj);
          });
          console.log("保存的数据---------------------------", data);
          await savePoint(data).then(() => {
            ElMessage.success("保存配置成功，即将进行跳转！");
          });
          await beforeInit();
          model.SetMdel("dashboard");
        })
        .catch(() => {
          return;
        })
        .finally(() => {
          var body = document.querySelector("body");
          body.style.cursor = "default";
          isZoom.value = false;
          model.Setedit(false);
        });
    }
  }
};

// 取消编辑模式
const exitEditModel = async () => {
  // exitEdit(eqData.value, beforeInit)
  eqData.value.forEach((item, index) => {
    if (item.editId) {
      if (index > -1) {
        eqData.value.splice(index, 1);
      }
    }
  });
  var body = document.querySelector("body");
  body.style.cursor = "default";
  await beforeInit();
  model.SetMdel("dashboard");
  model.Setedit(false);
  isZoom.value = false;
};

// 缩放编辑栏
const zoomEditModel = () => {
  isZoom.value = !isZoom.value;
};

// 设置点位告警信息
const setAlertMessageRecall = async () => {
  // 获取全部未处理告警消息，添加设备告警回显内容
  // const res = await getEquipmentIds("ALL");

  // var d = new Date();
  // var startTime =
  //   d.getFullYear() +
  //   "-" +
  //   (d.getMonth() + 1).toString().padStart(2, "0") +
  //   "-" +
  //   d
  //     .getDate()
  //     .toString()
  //     .padStart(2, "0");
  // var yday = new Date();
  // yday.setTime(yday.getTime() + 24 * 60 * 60 * 1000);
  // var endTime =
  //   yday.getFullYear() +
  //   "-" +
  //   (yday.getMonth() + 1).toString().padStart(2, "0") +
  //   "-" +
  //   yday
  //     .getDate()
  //     .toString()
  //     .padStart(2, "0");
  // let params = {
  //   equipmentIds: res.data,
  //   // startTime,
  //   // endTime,
  //   handleStatus: "0",
  // };
  // getAlertData(params)
  //   .then(({ data }) => {
  //     if (data && data.length) {
  //       console.log(data, "112233");

  //       data.forEach((wsMsg: any) => updateWsMsg(wsMsg));
  //     }
  //   })
  //   .finally(() => {
  //     getLocationAlertDetail();
  //   });
};
// 给予点位初始化显隐信息
const getPoint = async () => {
  let res: any = await getEqPoint();
  eqData.value = res.data;
  eqData.value.forEach((item) => {
    let obj = {
      wsMsg: [
        {
          ...initWsMsg,
        },
      ],
      popoverVisible: false,
    };
    item = Object.assign(item, obj);
  });
};
// 收到告警信息&&处理告警信息
const onAlertMessage = (data: any) => {
  updateWsMsg(data);
};
const onHandleMessage = (data: any) => {
  ElNotification.closeAll();
  updateHandle(data);
  // 刷新数据
};
const updateWsMsg = (data: any, cb?: Function) => {
  eqData.value = eqData.value.map((item: any) => {
    if (
      item.equipmentLocationCode == data.equipmentLocationCode &&
      data.alertGrade != "INFO" &&
      data.handleStatus == "0"
    ) {
      const index = item.wsMsg.findIndex(
        (item) => item.alertMessageId === data.alertMessageId
      );
      if (index > -1) {
        item.wsMsg.splice(index, 1);
      }
      item.wsMsg.unshift(data);
    }
    return item;
  });
  // getLocationAlertDetail();
};
const updateHandle = (data: any) => {
  eqData.value = eqData.value.map((item: any) => {
    const index = item.wsMsg.findIndex(
      (item) => item.alertMessageId === data.alertMessageId
    );
    if (index > -1) {
      item.wsMsg.splice(index, 1);
      if (item.wsMsg.length >= 1) {
      } else {
        if (item.status == "onLine") {
          item.icon = "static";
        } else {
          item.icon = "outline";
        }
      }
    }
    return item;
  });

  // getLocationAlertDetail();
};

const monitorCloseDialog = () => {
  uf.setCardShow(false);
};
const hkarCloseDialog = () => {
  uf.setHKARShow(false);
};

// 批量获取设备状态
// const setEqStatus = async (arr) => {
//   let data1 = [];
//   arr.forEach((item) => {
//     data1.push(item.equipmentLocationCode);
//   });
//   const { data } = await getEqStatus(data1);
//   eqData.value.forEach((item) => {
//     if (data[item.equipmentLocationCode]) {
//       const typeIndex = eqType.value.findIndex(
//         (type) => type.id == data[item.equipmentLocationCode].typeId
//       );
//       item.equipmentId = data[item.equipmentLocationCode].id;
//       item.name = data[item.equipmentLocationCode].name;
//       item.location = item.equipmentLocationCode;
//       item.type = eqType.value[typeIndex].name;
//       item.eqCode = data[item.equipmentLocationCode].eqCode;
//       item.eqModel = data[item.equipmentLocationCode].model;
//       item.hasAi = data[item.equipmentLocationCode].hasAi;
//       item.status =
//         data[item.equipmentLocationCode].status == "1" ? "onLine" : "outLine";
//       if (item.status == "outLine") {
//         item.icon = "outline";
//       } else {
//         item.icon = "static";
//       }
//     }
//   });
// };
const beforeInit = async () => {
  showPoint.value = false;
  // await getEquipmentType();
  // await getPoint();
  // await setEqStatus(eqData.value);
  // await setAlertMessageRecall();
  showPoint.value = true;
};
const handleAlert = (res) => {
  if (res.alertGrade != "INFO") {
    ElNotification.closeAll();
    onAlertMessage(res);
    Notification(res);
  }
};
const initback = () => {
  switch (locationIndex.value) {
    case 0:
      knowledgeBg.value = "knowledgeBg";
      break;

    case 1:
      knowledgeBg.value = "knowledgeBg1";
      break;
    case 2:
      knowledgeBg.value = "knowledgeBg2";
      break;
    case 3:
      knowledgeBg.value = "knowledgeBg3";
      break;
    case 4:
      knowledgeBg.value = "knowledgeBg4";
      break;
  }
  resetIDs(location.$state.locationArr[locationIndex.value].code);
};
const getEquipmentType = async () => {
  const res = await getEqType();
  eqType.value = res.data;
};
const changeSelect = (type, model, direction?) => {
  selectEqType.value = type;
  eqModel.value = model;
  eqdirection.value = direction;
  console.log(eqModel.value, "select");
};

// 鹰眼重连
const arhkreconnect = () => {
  // emits.emit("ARHK_RECONNECT");
};
const closePop = () => {
  cpopoverRef.value.forEach((item) => {
    if (item.showAi) {
      item.showAi = false;
    }
  });
};
onMounted(async () => {
  // emits.on("ALERT_MESSAGE", handleAlert);
  // emits.on("HANDLE_MESSAGE", onHandleMessage);
  emits.on("changeTab", reload);
  initback();
});
onBeforeMount(async () => {
  await beforeInit();
  initImage();
  emits.emit("CLOSE_VIDEO");
});
onUnmounted(() => {
  // emits.off("ALERT_MESSAGE", handleAlert);
  // emits.off("HANDLE_MESSAGE", onHandleMessage);
  emits.off("changeTab", reload);
});
useBeforeunload(beforeInit);
</script>
<style scoped lang="scss">
#layout {
  width: 100%;
  height: 100%;
  position: relative;
  background-size: 100% 100%;
  transition: background-image 0.3s ease-in-out;
}

.knowledgeBg {
  background: url("../../assets/image/dashboard/location/港口总览.jpg") center no-repeat;
}

.knowledgeBg1 {
  background: url("../../assets/image/dashboard/location/分区1.jpg") center no-repeat;
}

.knowledgeBg2 {
  background: url("../../assets/image/dashboard/location/分区2.jpg") center no-repeat;
}

.knowledgeBg3 {
  background: url("../../assets/image/dashboard/location/分区3.jpg") center no-repeat;
}

.knowledgeBg4 {
  background: url("../../assets/image/dashboard/location/分区4.jpg") center no-repeat;
}
</style>
